package com.iw.core.security.service;

import java.util.HashSet;
import java.util.Iterator;
import java.util.List;
import java.util.Set;

import org.hibernate.Query;
import org.hibernate.Session;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.security.core.GrantedAuthority;
import org.springframework.security.core.authority.SimpleGrantedAuthority;
import org.springframework.security.core.userdetails.UserDetails;
import org.springframework.security.core.userdetails.UserDetailsService;
import org.springframework.security.core.userdetails.UsernameNotFoundException;
import org.springframework.stereotype.Repository;

import com.iw.core.security.entity.Roles;
import com.iw.core.security.entity.Users;

@Repository("userServiceDetail")
public class UserDetailServiceImpl implements UserDetailsService {

    @Autowired
    private UsersService usersService;

    public UserDetails loadUserByUsername(String username) throws UsernameNotFoundException {

        // System.out.println("---------MyUserDetailServiceImpl:loadUserByUsername------正在加载用户名和密码，用户名为：" + username);
        // Users user = usersService.find("account", username);

        Session session = usersService.getBaseDao().getNewSession();
        session.beginTransaction();
        Query query = session.createQuery("from " + Users.class.getSimpleName() + " u where u.account = ?");
        query.setString(0, username);
        @SuppressWarnings("rawtypes")
        List list = query.list();
        if (list == null || list.isEmpty()) {
            throw new UsernameNotFoundException("用户不存在!");
        }
        Users user = (Users) list.get(0);
        if (!user.isEnable()) {
            throw new UsernameNotFoundException("用户已被禁用！");
        }
        // Hibernate.initialize(user.getRoles());

        boolean enabled = true; // 是否可用
        boolean accountNonExpired = true; // 是否过期
        boolean credentialsNonExpired = true;
        boolean accountNonLocked = true;

        Set<GrantedAuthority> authorities = new HashSet<GrantedAuthority>();
        Iterator<Roles> iterator = user.getRoles().iterator();
        boolean roleEnable = false;     //当前登陆的用户的所有角色是否被禁用了
        while (iterator.hasNext()) {
            Roles role = iterator.next();
            if (!roleEnable) {
                roleEnable = role.isEnable();
            }
            if (role.isEnable()) {    //可用的角色才给加权限
                GrantedAuthority ga = new SimpleGrantedAuthority(role.getType());
                authorities.add(ga);
            }
            // System.out.println(ga.getAuthority());
        }
        if (!roleEnable) {
            throw new UsernameNotFoundException("用户无权限！");
        }
        session.close();
        return new org.springframework.security.core.userdetails.User(user.getAccount(), user.getPassword(), enabled, accountNonExpired, credentialsNonExpired, accountNonLocked, authorities);
    }

}